package org.ting.j20250110_gobang.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.ting.j20250110_gobang.game.MatchRequest;
import org.ting.j20250110_gobang.game.MatchResponse;
import org.ting.j20250110_gobang.game.Matcher;
import org.ting.j20250110_gobang.game.OnlineUserManager;
import org.ting.j20250110_gobang.model.User;

@Component
public class MatchWebSocket extends TextWebSocketHandler {
    @Autowired
    OnlineUserManager onlineUser;
    @Autowired
    Matcher matcher;
    @Autowired
    ObjectMapper objectMapper; //处理json字符串
    //连接成功后执行
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //玩家上线
        try {
            System.out.println("================连接成功===============");
            //获取登录时储存在session中的用户信息，这里WebSocketSession在注册时通过拦截器获取到了session中的内容
            User user = (User)session.getAttributes().get("user");
            System.out.println("userId: " + user.getUserId());
            if(onlineUser.getFromHall(user.getUserId()) == null
            && onlineUser.getFromRoom(user.getUserId()) == null) {
                onlineUser.enterGameHall(user.getUserId(), session);
                System.out.println("用户：" + user.getUsername() + " 已上线");
            }else{
                //防止重复登录
                MatchResponse response = new MatchResponse();
                response.setMessage("repeat_login");
                response.setOk(false);
                response.setErrMsg("用户已在别处登录");
                System.out.println("用户已在别处登录");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                session.close();
            }

        }catch (NullPointerException e) {
            //e.printStackTrace();
            System.out.println("MatchWebSocket.afterConnectionEstablished 用户未登录");
            MatchResponse response = new MatchResponse();
            response.setMessage("no_login");
            response.setOk(true);
            response.setErrMsg("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }

    }
    //接收到请求后执行
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        MatchRequest request = objectMapper.readValue(message.getPayload(), MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if(request.getMessage().equals("startMatch")) {
            //开始匹配，把用户加入匹配队列
            matcher.add(user);
            response.setOk(true);
            response.setMessage("startMatch");
        }else if(request.getMessage().equals("stopMatch")) {
            //取消匹配，从匹配队列中移除用户
            matcher.remove(user);
            response.setOk(true);
            response.setMessage("stopMatch");
        }else{
            response.setOk(false);
            response.setErrMsg("非法请求");
        }
        //返回响应
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }
    //连接异常时执行
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //连接异常断开，玩家下线
        try {
            User user = (User)session.getAttributes().get("user");
            //防止重复登录时删除正常登录的在线信息
            if(onlineUser.getFromHall(user.getUserId()).equals(session)) {
                onlineUser.exitGameHall(user.getUserId());
                System.out.println("连接异常断开，用户：" + user.getUsername() + " 已下线");
                //用户可能还在匹配队列中
                matcher.remove(user);
            }
        }catch (NullPointerException e) {
            //e.printStackTrace();
            System.out.println("MatchWebSocket.handleTransportError 用户未登录");
        }
    }
    //连接正常断开后执行
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //连接正常断开，玩家下线
        try {
            User user = (User)session.getAttributes().get("user");

            //防止重复登录时删除正常登录的在线信息
            if(onlineUser.getFromHall(user.getUserId()).equals(session)) {
                onlineUser.exitGameHall(user.getUserId());
                System.out.println("连接正常断开，用户：" + user.getUsername() + " 已下线");
                //用户可能还在匹配队列中
                matcher.remove(user);
            }
        }catch (NullPointerException e) {
            //e.printStackTrace();
            System.out.println("MatchWebSocket.afterConnectionClosed 用户未登录");
        }
    }
}
